package com.flycms.web.activity;

import com.flycms.core.entity.PageVo;
import com.flycms.core.entity.RestDataVo;
import com.flycms.module.activity.enums.ActivityTypeEnum;
import com.flycms.module.activity.model.Activity;
import com.flycms.module.activity.model.ActivityDetail;
import com.flycms.module.activity.model.ActivityTag;
import com.flycms.module.activity.param.ActivityInfo;
import com.flycms.module.activity.param.ActivityQueryParam;
import com.flycms.module.activity.service.ActivityService;
import com.flycms.utils.ConvertUtils;
import com.flycms.web.activity.vo.ActivityDetailVO;
import com.flycms.web.activity.vo.ActivityVO;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author modenglang
 */

@RestController
@Slf4j
public class ActivityController {

    @Autowired
    private ActivityService activityService;

    /**
     * 更新活动
     *
     * @param param 更新参数
     * @return 更新结果
     */
    @PutMapping("/system/activity/update")
    public RestDataVo update(@RequestBody ActivityInfo param) {
        try {
            activityService.update(param);
        } catch (Exception e) {
            log.error("更新活动異常:", e);
            return RestDataVo.ERROR("更新失败");
        }
        return RestDataVo.OK("更新成功");
    }

    /**
     * 保存活动
     *
     * @param param 活动参数
     * @return 保存结果
     */
    @PostMapping("/system/activity/save")
    public RestDataVo save(@RequestBody ActivityInfo param) {
        try {
            activityService.save(param);
        } catch (Exception e) {
            log.error("保存活动异常:", e);
            return RestDataVo.ERROR("保存失败");
        }
        return RestDataVo.OK("保存成功");
    }

    /**
     * 删除活动
     *
     * @param id 活动ID
     * @return 删除结果
     */
    @DeleteMapping("/system/activity/del/{id}")
    public RestDataVo del(@PathVariable("id") Long id) {
        try {
            activityService.del(id);
        } catch (Exception e) {
            log.error("删除活动异常:", e);
            return RestDataVo.ERROR("删除失败");
        }
        return RestDataVo.OK("删除成功");
    }

    /**
     * 根据类型查找活动列表
     *
     * @param param
     * @return 返回结果 查询不到返回空集合
     */
    @GetMapping("/activity/list")
    public RestDataVo getActivityList(ActivityQueryParam param) {
        PageVo<Activity> activityPage = activityService.getActivityPage(param);
        if (CollectionUtils.isEmpty(activityPage.getList())) {
            return RestDataVo.PAGE(activityPage.getList(), activityPage.getPageNum(), param.getPageSize(), 0);
        }
        List<ActivityVO> activityVOS = ConvertUtils.sourceToTarget(activityPage.getList(), ActivityVO.class);
        if (Objects.nonNull(param.getType())) {
            String type = ActivityTypeEnum.getDescByCode(param.getType());
            activityVOS.forEach(a -> a.setType(type));
        } else {
            List<Long> ids = activityVOS.stream().map(ActivityVO::getId).collect(Collectors.toList());
            List<ActivityTag> tags = activityService.getTagsByActivityIds(ids);
            if (CollectionUtils.isNotEmpty(tags)) {
                Map<Long, List<ActivityTag>> tagMap = tags.stream().collect(Collectors.groupingBy(ActivityTag::getActivityId));
                activityVOS.forEach(a -> {
                    if (Objects.nonNull(tagMap.get(a.getId()))) {
                        List<ActivityTag> idTags = tagMap.get(a.getId());
                        List<String> tagList = idTags.stream().map(ActivityTag::getTagName).collect(Collectors.toList());
                        String type = ConvertUtils.join(tagList);
                        a.setType(type);
                    }
                });
            }
        }
        return RestDataVo.PAGE(activityVOS, activityPage.getPageNum(), param.getPageSize(), activityPage.getCount());
    }

    /**
     * 根据类型查找活动列表
     *
     * @param param
     * @return 返回结果 查询不到返回空集合
     */
    @GetMapping("/system/activity/list")
    public RestDataVo getSysActivityList(ActivityQueryParam param) {
        PageVo<Activity> activityPage = activityService.getActivityPage(param);
        if (CollectionUtils.isEmpty(activityPage.getList())) {
            return RestDataVo.PAGE(activityPage.getList(), activityPage.getPageNum(), param.getPageSize(), 0);
        }
        List<ActivityVO> activityVOS = ConvertUtils.sourceToTarget(activityPage.getList(), ActivityVO.class);
        List<Long> ids = activityVOS.stream().map(ActivityVO::getId).collect(Collectors.toList());
        List<ActivityTag> tags = activityService.getTagsByActivityIds(ids);
        if (CollectionUtils.isNotEmpty(tags)) {
            Map<Long, List<ActivityTag>> tagMap = tags.stream().collect(Collectors.groupingBy(ActivityTag::getActivityId));
            activityVOS.forEach(a -> {
                if (Objects.nonNull(tagMap.get(a.getId()))) {
                    List<ActivityTag> idTags = tagMap.get(a.getId());
                    List<String> tagList = idTags.stream().map(ActivityTag::getTagName).collect(Collectors.toList());
                    String type = ConvertUtils.join(tagList);
                    a.setType(type);
                }
            });
        }
        return RestDataVo.PAGE(activityVOS, activityPage.getPageNum(), param.getPageSize(), activityPage.getCount());
    }

    /**
     * 根据活动ID查询活动明细
     *
     * @param id ID
     * @return 活动明细数据
     */
    @GetMapping("/activity/{id}")
    public RestDataVo getActivityList(@PathVariable("id") Long id) {
        ActivityDetail activityDetail = activityService.getDetailByActivityId(id);
        if (Objects.isNull(activityDetail)) {
            return RestDataVo.OK(null);
        }
        //查询上一篇
        Activity preActivity = activityService.getPreActivity(id);
        //查询下一篇
        Activity nextActivity = activityService.getNextActivity(id);
        ActivityDetailVO activityDetailVO = ConvertUtils.sourceToTarget(activityDetail, ActivityDetailVO.class);
        if (Objects.nonNull(preActivity)) {
            activityDetailVO.setPreActivityId(preActivity.getId());
            activityDetailVO.setPreActivityName(preActivity.getActivityName());
        }
        if (Objects.nonNull(nextActivity)) {
            activityDetailVO.setNextActivityId(nextActivity.getId());
            activityDetailVO.setNextActivityName(nextActivity.getActivityName());
        }
        //查询标签
        List<Long> ids = Lists.newArrayList(activityDetail.getActivityId());
        List<ActivityTag> tags = activityService.getTagsByActivityIds(ids);
        activityDetailVO.setTags(tags);
        return RestDataVo.OK(activityDetailVO);
    }

    @GetMapping("/system/activity/{id}")
    public RestDataVo getSysActivityList(@PathVariable("id") Long id) {
        Activity activity = activityService.getActivityById(id);
        if (Objects.isNull(activity)){
            return RestDataVo.OK(null);
        }
        ActivityVO activityVO = ConvertUtils.sourceToTarget(activity, ActivityVO.class);
        ActivityDetail activityDetail = activityService.getDetailByActivityId(id);
        activityVO.setDetail(activityDetail);
        //查询标签
        List<Long> ids = Lists.newArrayList(id);
        List<ActivityTag> tags = activityService.getTagsByActivityIds(ids);
        activityVO.setTags(tags);
        return RestDataVo.OK(activityVO);
    }

    /**
     * 根据类型查找最新
     *
     * @return 返回结果 查询不到返回空集合
     */
    @GetMapping("/activity/list/new")
    public RestDataVo getNewActivityList() {
        List<Activity> activities = activityService.getNewActivityList();
        if (CollectionUtils.isEmpty(activities)) {
            return RestDataVo.OK(Lists.newArrayList());
        }
        List<ActivityVO> activityVOS = ConvertUtils.sourceToTarget(activities, ActivityVO.class);
        return RestDataVo.OK(activityVOS);
    }

}
